import preferences from '@ohos.data.preferences';

class preference {
  private preferenceMap: Map<String, preferences.Preferences> = new Map()

  async load(context, name: string) {
    try {
      let pref = await preferences.getPreferences(context, name)
      this.preferenceMap.set(name, pref)
      console.log("test", `load preference success, name:${name}`)
    } catch (e) {
      console.log("test", `load preference fail, name:${name} err : ${e}`)
    }
  }

  async get(name: string, key: string, def?: preferences.ValueType) {
    if (this.preferenceMap.has(name)) {
      try {
        let obj = this.preferenceMap.get(name)
        let val = await obj.get(key, def)
        console.log("test", `get preference value success, ${name}.${key}=${val}`)
        return val
      } catch (e) {
        console.log("test", `get preference value fail, ${name}, err:${e}`)
      }
    } else {
      console.log("test", `get preference value fail, ${name} is not init`)
    }
  }

  async put(name: string, key: string, val: preferences.ValueType) {
    if (this.preferenceMap.has(name)) {
      try {
        let obj = this.preferenceMap.get(name)
        await obj.put(key, val)
        await obj.flush()
        console.log(`test`, `put ${name}.${key}=${val} success `)
      } catch (e) {
        console.log("test", `get preference value fail, ${name}, err:${e}`)
      }
    } else {
      console.log("test", `get preference value fail, ${name} is not init`)
    }
  }
}

const preferenceUtil = new preference()

export default preferenceUtil as preference